﻿using CommunityToolkit.Mvvm.Input;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WPF.Core;
using WPF.Core.Services;

namespace WPF.Zero.ViewModels
{
    /// <summary>
    /// LoginView作为对话框
    /// </summary>
    public partial class LoginViewModel : DialogViewModel
    {
        private readonly IDialogService dialog;
        private readonly UserService appService;

        public LoginViewModel(IDialogService dialog, UserService appService)
        {
            this.dialog = dialog;
            this.appService = appService;
        }

        private int selectedIndex;

        public int SelectedIndex
        {
            get { return selectedIndex; }
            set
            {
                selectedIndex = value;
                UpdateLanguage();
                RaisePropertyChanged();
            }
        }

        private string userName;
        private string password;

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName
        {
            get { return userName; }
            set { userName = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 密码
        /// </summary>
        public string Password
        {
            get { return password; }
            set { password = value; RaisePropertyChanged(); }
        }

        [RelayCommand]
        private void Register()
        {
            dialog.ShowDialog("RegisterView");
        }

        [RelayCommand]
        private async Task Login()
        {
            if (string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(Password)) return;

            //IsBusy
            await SetBusyAsync(async () =>
            {  
                var loginResult = await appService.LoginAsync(UserName, Password);
                if (loginResult == null)
                {
                    MessageBox.Show("用户名或密码错误！");
                    return;
                }
                await Task.Delay(1000);
                //缓存当前用户信息
                OnDialogClosed();
            });
        }

        private void UpdateLanguage()
        {
            var language = SelectedIndex == 0 ? "zh-CN" : "en-US";

            var resource = App.Current.Resources.MergedDictionaries.FirstOrDefault(t => t.Source != null &&
             t.Source.OriginalString.Contains(language));

            if (resource != null)
                App.Current.Resources.MergedDictionaries.Remove(resource);

            App.Current.Resources.MergedDictionaries.Add(resource);
        }
    }
}
